import {autoUpdater} from 'electron-updater'
import Global from '../renderer/Global'

const electron = require('electron');
const ipcMain = electron.ipcMain;
const globalShortcut = electron.globalShortcut;
const dialog = electron.dialog;
const Menu = electron.Menu;
const Notification = electron.Notification;
const BrowserWindow = electron.BrowserWindow;
const app = electron.app;
const Tray = electron.Tray;
const shell = electron.shell;
const path = require('path');

const DEBUG = process.env.NODE_ENV === 'development';

global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\');
const winURL = DEBUG ? `http://localhost:9080` : `file://${__dirname}/index.html`;

// app.setLoginItemSettings({openAtLogin: true, openAsHidden: true}); // 开机自启

let tray, mainWindow;

function createWindow() {
    mainWindow = new BrowserWindow({
        show: false,
        webPreferences: {webSecurity: false},
        useContentSize: true,
        height: 720,
        width: 1024,
        darkTheme: true,
    });
    mainWindow.webContents.closeDevTools();
    mainWindow.loadURL(winURL);
    mainWindow.on('ready-to-show', function () {
        mainWindow.show();
        mainWindow.focus();
    });
    mainWindow.on('closed', () => mainWindow = null);
    if (process.platform === "darwin") {
        let content = mainWindow.webContents;
        globalShortcut.register("CommandOrControl+C", () => content.copy());
        globalShortcut.register("CommandOrControl+V", () => content.paste());
        globalShortcut.register("CommandOrControl+A", () => content.selectAll());
        globalShortcut.register("CommandOrControl+X", () => content.cut());
        globalShortcut.register("CommandOrControl+Z", () => content.undo());
    }
    app.setAppUserModelId("com.yangzhe.yfree_electron");
    if (!DEBUG) {
        autoUpdater.setFeedURL(`http://???/${process.platform}`);
        let interval = setInterval(() => autoUpdater.checkForUpdates(), 60000);
        autoUpdater.on('update-downloaded', () => {
            dialog.showMessageBox({
                type: 'info',
                buttons: ['升级', '稍后'],
                message: "检测到升级",
                detail: '是否升级？'
            }).then((returnValue) => {
                if (returnValue.response === 0) {
                    clearInterval(interval);
                    autoUpdater.quitAndInstall();
                }
            });
        });
    }
    Menu.setApplicationMenu(Menu.buildFromTemplate([
        {label: '自定义菜单1', submenu: [{label: '欢迎使用', click: () => shell.openExternal("https://gitee.com/2425116357/YFree_Electron")}]},
        {
            label: '自定义菜单2',
            submenu: [
                {
                    label: '最小化',
                    accelerator: 'CmdOrCtrl+M',
                    role: 'minimize',
                },
                {
                    label: '关闭',
                    accelerator: 'CmdOrCtrl+W',
                    role: 'close',
                },
                {type: 'separator'},
                {
                    label: '重新打开窗口',
                    accelerator: 'CmdOrCtrl+Shift+T',
                    enabled: true,
                    key: 'reopenMenuItem',
                    click: () => app.emit('activate'),
                },
            ],
        },
    ]));
    if (process.platform === "darwin")
        app.dock.setMenu(Menu.getApplicationMenu());
    tray = process.platform === "darwin" ? new Tray(`${__static}/tray.png`) : new Tray(`${__static}/tray.ico`);
    tray.setContextMenu(Menu.buildFromTemplate([
        {label: '显示窗口', click: () => mainWindow.show(),},
        {label: '隐藏窗口', click: () => mainWindow.hide(),},
        {label: '退出', click: () => app.quit(),},
    ]));
    let notify = new Notification({
        title: "title",
        subtitle: "subtitle",
        body: "body",
    });
    notify.on("click", () => mainWindow.show());
    notify.show();
}

app.on('ready', createWindow);

app.on('window-all-closed', () => app.quit());

app.on('activate', () => {
    if (mainWindow === null) createWindow();
});

ipcMain.on(Global.IFinal.IPC.win_min, (event, arg) => {
    BrowserWindow.getFocusedWindow().minimize();
});

ipcMain.on(Global.IFinal.IPC.win_max, (event, arg) => {
    let win = BrowserWindow.getFocusedWindow();
    if (win.isMaximized()) win.unmaximize();
    else win.maximize();
});

ipcMain.on(Global.IFinal.IPC.win_full, (event, arg) => {
    let win = BrowserWindow.getFocusedWindow();
    win.setFullScreen(!win.isFullScreen())
});

ipcMain.on(Global.IFinal.IPC.win_close, (event, arg) => {
    BrowserWindow.getFocusedWindow().close();
});

// ipcMain.on('goMain', (event, arg) => {
//     let mainPage = new BrowserWindow({
//         height: 720,
//         width: 1024,
//         webPreferences: {webSecurity: false},
//     });
//     mainPage.loadURL(`${winURL}${DEBUG ? "/#/" : "#"}main`);
//     mainPage.on('close', () => mainPage = null);
//     if (mainWindow) mainWindow.close();
// });
